﻿unit Unit1;
interface

uses
Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,
Dialogs,StdCtrls,ExtCtrls,Menus,AppEvnts,shellapi,Registry,DateUtils,IniFiles,
  System.ImageList, Vcl.ImgList;
const
  WM_MYUSER = WM_USER + 111;
type 
 TOSVersion = (osUnknown, os95, os98, osME, osNT3, osNT4, os2K, osXP, os2K3);
type 
   TForm1 = class(TForm)
   Timer1: TTimer; 
   Timer2: TTimer;
   ApplicationEvents1: TApplicationEvents;
   PopupMenu1: TPopupMenu;
   Edit1: TEdit; 
   Edit2: TEdit;
   Label1: TLabel;
   Label2: TLabel; 
   Label3: TLabel; 
   Btn_OK: TButton; 
   Btn_Abort: TButton;
    TimeSet: TMenuItem;
    Exit: TMenuItem;
    Timer3: TTimer;
    Label4: TLabel;
    Label5: TLabel;
    Timer4: TTimer;
    Image1: TImage;
    Image2: TImage;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Timer5: TTimer;
    Button4: TButton;
    Memo2: TMemo;
    Button5: TButton;
    suoping: TTimer;
    ImageList1: TImageList;
   procedure Timer1Timer(Sender: TObject); 
   procedure TrayMenu(Var Msg:TMessage); message WM_USER;
   procedure TimeSetClick(Sender: TObject);
   procedure ExitClick(Sender: TObject);
   procedure Btn_OKClick(Sender: TObject); 
   procedure Btn_AbortClick(Sender: TObject);
   procedure Timer2Timer(Sender: TObject);
   procedure Edit2KeyPress(Sender: TObject; var Key: Char); 
   procedure WMQueryEndSession (var Msg : TWMQueryEndSession); 
   message WM_QueryEndSession; 
   procedure FormCreate(Sender: TObject); 
   procedure FormDestroy(Sender: TObject); 
   procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure FormResize(Sender: TObject);
    procedure ApplicationEvents1Minimize(Sender: TObject);
    procedure Timer3Timer(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure Edit2Enter(Sender: TObject);
    procedure Timer4Timer(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Timer5Timer(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
    procedure suopingTimer(Sender: TObject);
private
 { Private declarations }
 shaBool:Boolean ;//托盤閃爍
 Tray:NOTIFYICONDATA;
 Po1:Tpoint;
 procedure ShowInTray();
 procedure RefreshTrayIcon();
 function GetOS: TOSVersion;
 function GetSysTrayWnd(): HWND;
 procedure MYWndProc(var Msg: Tmessage); message 1010;
public 
 { Public declarations }
end; 

var 
   Form1: TForm1;
   P,Ti1:Pchar; 
   Flags:Longint;
   Autostartshotdown:Integer;
   i:integer; 
   {關機延時時間} //?机延???
   TimeDelay:integer;
   atom:integer;
   closemenu1:TPoint;
   time_enter,time_exit:string;
   enterbool,cancelbool,clickInTray:Boolean;      //enterbool是判斷是否進入過edit2 ，cancelbool用戶是否點擊了取消，點擊取消為ture否則為false
   OldX,OldY:integer; //定義全局變量
   suoping_flig:Integer ;//鎖屏程式是否有開啟過標誌 ，鎖屏有開啟過又被不正常關閉，就啟動自動關機； (0表示鎖屏，沒有開啟過；；1表示鎖屏程式已經開啟，2表示鎖屏正常關閉，3表示鎖屏程式非正常關閉)

implementation
uses  MessageHint_u,MessageShow_u;
 {$R *.dfm}
 /////////////////////////
 function IsWin64: Boolean;
var
  Kernel32Handle: THandle;
  IsWow64Process: function(Handle: Windows.THandle; var Res: Windows.BOOL): Windows.BOOL; stdcall;
  GetNativeSystemInfo: procedure(var lpSystemInfo: TSystemInfo); stdcall;
  isWoW64: Bool;
  SystemInfo: TSystemInfo;
const
  PROCESSOR_ARCHITECTURE_AMD64 = 9;
  PROCESSOR_ARCHITECTURE_IA64 = 6;
begin
  Kernel32Handle := GetModuleHandle('KERNEL32.DLL');
  if Kernel32Handle = 0 then
    Kernel32Handle := LoadLibrary('KERNEL32.DLL');
  if Kernel32Handle <> 0 then
  begin
    IsWOW64Process := GetProcAddress(Kernel32Handle,'IsWow64Process');
    GetNativeSystemInfo := GetProcAddress(Kernel32Handle,'GetNativeSystemInfo');
    if Assigned(IsWow64Process) then
    begin
      IsWow64Process(GetCurrentProcess,isWoW64);
      Result := isWoW64 and Assigned(GetNativeSystemInfo);
      if Result then
      begin
        GetNativeSystemInfo(SystemInfo);
        Result := (SystemInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64) or
                  (SystemInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_IA64);
      end;
    end
    else Result := False;
  end
  else Result := False;
end;
 ////////////////////////////////
procedure SetXwForegroundWindow(AHandle: Thandle);
var
  hFgWin: Thandle;
  hFgThread: Thandle;
begin

  ShowWindow(AHandle, SW_NORMAL);

  hFgWin := GetForegroundWindow;
  hFgThread := GetWindowThreadProcessID(hFgWin, nil);

  if AttachThreadInput(GetCurrentThreadID, hFgThread, true) then
  begin
    SetForegroundWindow(AHandle);
    AttachThreadInput(GetCurrentThreadID, hFgThread, false);
  end
  else
    SetForegroundWindow(AHandle);

end;

{沒有到關機時間，系統要關閉計算機，截獲關機消息
wm_queryendsession，讓用戶決定是否關機} //?有到?机??，系?要???算机，截??机消息 wm_queryendsession，?用?定是否?机
procedure TForm1.WMQueryEndSession (var Msg : TWMQueryEndSession);
begin
 if MessageDlg('Do you really want to power off ?',mtConfirmation,[mbYes,mbNo], 0) = mrNo then
   Msg.Result := 0 
 else
   Msg.Result := 1;
 end;

{判斷時間格式S是否有效}  //判???格式S是否有效

function IsValidTime(s:string):bool; 
begin 
 if  Length(s)<>5 then
   IsValidTime:=False
 else 
 begin
   if(s[1]<'0')or(s[1]>'2')or(s[2]<'0')or
     (s[2]>'9') or (s[3] <> ':') or
     (s[4]<'0') or (s[4]>'5') or
     (s[5]<'0') or (s[5]>'9')then
     IsValidTime:=False
   else
     IsValidTime:=True; 
 end;
end; 


{判斷操作系統，確定關機方式}  //判?操作系?，确定?机方式

function GetOperatingSystem: string;
var osVerInfo: TOSVersionInfo;
begin
  Result :='';
  osVerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
  if GetVersionEx(osVerInfo) then
    case osVerInfo.dwPlatformId of
      VER_PLATFORM_WIN32_NT:
        begin
          Result := 'Windows NT/2000/XP'
        end;
      VER_PLATFORM_WIN32_WINDOWS:
        begin
          Result := 'Windows 95/98/98SE/Me';
        end;
    end;
end;


{獲得計算機名} //?得?算机名

function GetComputerName: string;
var
 buffer: array[0..MAX_COMPUTERNAME_LENGTH + 1] of Char;
 Size: Cardinal;
begin
  Size := MAX_COMPUTERNAME_LENGTH + 1;
  Windows.GetComputerName(@buffer, Size);
  Result := strpas(buffer);
end;


{定時關機函數，各參數如下： //定??机函?，各??如下：
Computer: 計算機名;Msg:顯示提示信息; //?算机名，?示提示信息
Time:時間延時; Force:是否強制關機;  //??延?，是否?制?机
Reboot: 是否重新啟動}     // 是否重新??
function TimedShutDown(Computer: string; Msg: string;
 Time: Word; Force: Boolean; Reboot: Boolean): Boolean;
var
 rl: Cardinal;
 //hToken: Cardinal;//XE8中不能這麼寫
 hToken: THandle ;
 tkp: TOKEN_PRIVILEGES;
begin
{獲得用戶關機特權，僅對Windows NT/2000/XP}   //?取用??机特?，??
  OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken);
  if LookupPrivilegeValue(nil, 'SeShutdownPrivilege', tkp.Privileges[0].Luid) then
  begin
    tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
    tkp.PrivilegeCount := 1;
    AdjustTokenPrivileges(hToken, False, tkp, 0, nil, rl);
  end;
  Result := InitiateSystemShutdown(PChar(Computer), PChar(Msg), Time, Force, Reboot)
  {fResult =InitiateSystemShutdown(
  NULL, // 要关的计算机用户名
  "由于系统不稳定，WINDOWS将在上面的时间内关机，请做好保存工作!", // 显示消息
  0, // 关机所需的时间
  FALSE, // 是否提示用户
  FALSE); //设为TRUE为重起，设为FALSE为关机}
end;

{窗體最小化，顯示到托盤}  //窗体最小化，?示到托?

procedure tForm1.ShowInTray;

Begin
 Tray.cbSize:=sizeof(Tray);
 Tray.Wnd:=Self.Handle;
 Tray.uFlags:=NIF_ICON+NIF_MESSAGE+NIF_TIP;
 Tray.uCallbackMessage:=WM_USER;
 Tray.hIcon:=application.Icon.Handle ;
 Tray.szTip:='Timing Shutdown'; //定??机
 Shell_NotifyIcon(NIM_ADD,@Tray);
End;

procedure TForm1.suopingTimer(Sender: TObject);
begin
   //if  then

  //
end;

{右鍵單擊托盤中的圖標，顯示快捷菜單} //右?托?的??，?示快捷菜?

procedure TForm1.TrayMenu(var Msg:TMessage);

Begin
  GetCursorPos(Po1);
  begin
    if (Msg.LParam = WM_LBUTTONDOWN) and (not clickInTray) then
    Begin
    //扢离敦諳弇衾郔階脯
      SetWindowPos(Handle,HWND_TOPMOST,Left,Top,Width,Height, SWP_SHOWWINDOW);
      ShowWindow(Application.Handle,SW_SHOWNORMAL );
      SetWindowPos(Handle,HWND_NOTOPMOST,Left,Top,Width,Height, SWP_SHOWWINDOW);
      clickInTray:= not clickInTray;
    End
    else
    if (Msg.LParam = WM_LBUTTONDOWN) and (clickInTray) then
    begin
      ShowWindow(Application.Handle,sw_minimize);
      ShowWindow(Application.Handle,sw_hide);
      ShowInTray;
      clickInTray:= not clickInTray;
    end
    else
    if Msg.LParam=WM_RBUTTONDOWN then
    begin
      SetForegroundWindow(Self.Handle);
      PopupMenu1.Popup(Po1.X  ,Po1.Y );
    end
    else
     // if Assigned(PopupMenu) then
     //  ShowMessage('111');
  end;
End;

procedure TForm1.Timer1Timer(Sender: TObject); //關機
begin 
  Edit1.Text:=FormatDateTime('hh:mm', Now);
  {兩個時間相等，計算機將在TimeDelay內關機}  //????相等，?算机?在TIMEDELAY??机
  if (edit1.text=edit2.Text)and (not cancelbool ) then
  Begin
    Application.Restore;
    TimeDelay:=30;
    timer1.Enabled:=False;
    Edit2.ReadOnly :=True;
    if GetOperatingSystem='Windows NT/2000/XP' then
    begin
      {調用系統關機窗體，僅限Windows NT/2000/XP。} //?用系??机窗体，?限
      TimedShutDown(getcomputername,  'The system will turn off automatically after 30 seconds !',   //系??要?机
      TimeDelay, true, false);
      btn_abort.Enabled :=true;
      timer2.Enabled :=true;
    end;
    if GetOperatingSystem='Windows 95/98/98SE/Me' then
    begin
      timer2.Enabled :=true;
      {在頂層顯示本程序窗體，顯示時間倒計時}  //在???示本程序窗体，?示??倒??
      Application.Restore;
      SetWindowPos(Handle,HWND_TOPMOST,Left,Top,Width,Height,
               SWP_NOACTIVATE);
    end;
  end;
end;

procedure TForm1.Timer2Timer(Sender: TObject);//進入關機倒計時
begin
  btn_abort.Enabled :=true;
  shaBool := not shaBool ;
  if not shaBool  then //托盤圖標閃爍
  begin
    Tray.hIcon:=Image1.Picture.Icon.Handle ;
    Shell_NotifyIcon(NIM_MODIFY,@Tray);
  end
  else
  begin
    Tray.hIcon:=Image2.Picture.Icon.Handle ;
    Shell_NotifyIcon(NIM_MODIFY,@Tray);
  end;

  Application.ProcessMessages;
  label3.Caption := inttostr(timedelay)+' seconds later, the computer automatically shut down !';   //距?机?有  秒
  if  Assigned(Form1)   then
  begin
     SetXwForegroundWindow(Form1.Handle);
  end;
  Windows.Beep(600, 300);
  if timedelay>0 then
    timedelay:=timedelay-1
  else
  begin
    timer2.Enabled :=false;
    {強制Windows 95/98/98SE/Me關機}   //?制?机
    ExitWindowsEx(EWX_SHUTDOWN,0);//ExitWindowsEx(EWX_SHUTDOWN+EWX_FORCE,0);
  end;
end;

{通過PopupMenu1定義的快捷菜單，包括’設置關機時間‘和’退出‘  //籵徹諷璃PopupMenu1隅砱腔辦豎粕等ㄛ婦嬤"扢离壽儂奀潔"睿"豖堤"﹝

PopupMenu1的AutoPopup為False；下面為'設置關機時間'}      //PopupMenu1腔AutoPopup峈Falseㄛ狟醱岆"扢离壽儂奀潔"腔測鎢
procedure TForm1.TimeSetClick(Sender: TObject);
begin
  {設置本程的頂層窗體}    //扢离掛最唗敦諳弇衾郔階脯
  SetWindowPos(Handle,HWND_TOPMOST,Left,Top,Width,Height,
                           SWP_NOACTIVATE);
  ShowWindow(Application.Handle,SW_NORMAL);
  //edit2.SetFocus ;
  //edit2.SelectAll ;
  Po1.x:=0;
  Po1.y:=0;
end;

{快捷菜單退出代碼}    //辦豎粕等笢"豖堤"腔測鎢

procedure TForm1.ExitClick(Sender: TObject);
begin 
  {倒計時開始，禁止關閉窗體}     //彆眒冪羲宎給暮奀ㄛ輦砦豖堤ㄛ奧岆珆尨最唗敦諳
  if Timer2.Enabled=false then
  begin
    Application.Terminate;
  end
  else
    ShowWindow(Application.Handle,SW_NORMAL);
end;

{確定按鈕}       // 隅偌聽

procedure TForm1.Btn_OKClick(Sender: TObject);
begin

   if  btn_abort.Enabled = True  then
   begin
    Abort ;
   end;
  Timer3.Enabled:=False ;
  enterbool :=false;
  cancelbool :=False;
  btn_abort.Enabled :=false;
  label3.Caption :='Hint:Time format is HH:MM';     //  枑尨ㄩ壽儂奀潔跡宒﹛
  if timer1.Enabled =false then timer1.Enabled :=true;
{關機時間設置有效，}    // 壽儂奀潔扢离衄虴ㄛ最唗蔚珆尨婓迖攫笢ㄛ拸虴寀枑尨﹝
  if IsValidTime(edit2.Text) then
  begin
    ShowWindow(Application.Handle,sw_minimize);
    ShowWindow(Application.Handle,sw_hide);
    ShowInTray;
    clickInTray:=False ;
    label3.Caption :='The computer will turn off automatically at '+edit2.Text+' !';
  end
  else
    showmessage('Hint: Wrong time format! '+chr(13)+    //   枑尨ㄩ奀潔跡宒渣昫ㄛ
    'Please enter the correct time format HH:MM ');     //  怀淏腔壽儂奀潔﹛HH:MM﹝
end;


{取消關機}    // 秏壽儂偌聽

procedure TForm1.Btn_AbortClick(Sender: TObject);
begin
  if   GetOperatingSystem='Windows NT/2000/XP' then
{對於Windows NT/2000/XP,取消關機}    //勤衾Windows﹛NT/2000/XP,秏壽儂
  begin
     AbortSystemShutdown(pchar(getcomputername));

  end;
{停止倒計時}   // 礿砦給暮奀
  if timer2.Enabled =true then
  begin
    timer2.Enabled :=false;
    Edit2.ReadOnly:=false ;
    enterbool :=false;
    cancelbool :=True;
    Label3 .Caption :=' Scheduled shutdown has been canceled !';

    Timer1.Enabled :=True;
  end;
  btn_abort.Enabled :=false;
  Tray.hIcon:=Application.Icon.Handle ;
  Shell_NotifyIcon(NIM_MODIFY,@Tray);
end;

{輸入關機時間，回車}  // 怀壽儂奀潔綴ㄛ褫眻諉偌隙陬

procedure TForm1.Edit2KeyPress(Sender: TObject; var Key: Char);
begin
  if(key=#13) then
    Btn_OK.Click;
end; 

{尋找系統原子表，看程序是否運行}   // 刲扆炵苀埻赽桶艘岆瘁最唗眒堍俴

procedure TForm1.FormCreate(Sender: TObject);
//var i:Integer;
 // ps: array[0..254] of Char;
var
  Reg:TRegistry;
  rl: Cardinal;
 //hToken: Cardinal;//XE8中不能這麼寫
 hToken: THandle ;
 tkp: TOKEN_PRIVILEGES;

 //
  TPPrev, TP: TTokenPrivileges;
  TokenHandle: THandle;
  dwRetLen: DWORD;
  lpLuid: TLargeInteger;
 //
begin
  {ar
 rl: Cardinal;
 //hToken: Cardinal;//XE8中不能這麼寫
 hToken: THandle ;
 tkp: TOKEN_PRIVILEGES;
begin
{獲得用戶關機特權，僅對Windows NT/2000/XP}   //?取用??机特?，??
  {OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken);
  if LookupPrivilegeValue(nil, 'SeDebugPrivilege', tkp.Privileges[0].Luid) then
  begin
    tkp.PrivilegeCount := 1;
    tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
    AdjustTokenPrivileges(hToken, False, tkp, 0, nil, rl);
    if GetLastError<>ERROR_SUCCESS  then
      ShowMessage('權限獲取失敗！！');

  end; } {
  OpenProcessToken(GetCurrentProcess, TOKEN_ALL_ACCESS, TokenHandle);
  if (LookupPrivilegeValue(nil, 'SeDebugPrivilege', lpLuid)) then
  begin
      TP.PrivilegeCount := 1;
      TP.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
      TP.Privileges[0].Luid := lpLuid;
      AdjustTokenPrivileges(TokenHandle, False, TP, SizeOf(TPPrev), TPPrev, dwRetLen);
    if GetLastError<>ERROR_SUCCESS  then
      ShowMessage('權限獲取失敗！！');
  end;
  CloseHandle(TokenHandle); }

  Reg:=TRegistry.Create(KEY_ALL_ACCESS); //斐膘珨跺陔瑩
  Reg.RootKey:=HKEY_LOCAL_MACHINE; //蔚跦瑩扢离峈HKEY_LOCAL_MACHINE
  {if  IsWin64 then
    Reg.OpenKey('\SOFTWARE\Microsoft\windows\CurrentVersion\Run',true)
  else
    Reg.OpenKey('\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run',true);//湖羲珨跺瑩
  }

  reg.openkeyreadonly('\SOFTWARE\Microsoft\windows\CurrentVersion\Run');
  //if Reg.ValueExists('MyTimeHint') then
  //ShowMessage('1111');
    //reg.DeleteValue('TimeHint');
  //if not Reg.ValueExists('MyTimeHint') then
  // if  Reg.ValueExists ('MyTimeHint') then
  //   showmessage('djghsdj');
  if not Reg.ValueExists ('MyTimeHint') then
    Reg.WriteString('MyTimeHint',Application.ExeName); //婓Reg涴跺瑩笢迡杅擂靡備睿杅擂杅硉
  Reg.CloseKey;
  Reg.Free;

  enterbool:=False;
  cancelbool :=False ;
  clickInTray:=False ;
  Edit1.text:=FormatDateTime('hh:mm', Now);
  
  //ShowMessage('系統自動設定關機時間為：19:50,自動關機設定將在一分鐘后啟動');
   {如果沒有運行，則在表中增加信息 } //彆羶堍俴寀婓桶笢崝樓陓洘
  if GlobalFindAtom('PROGRAM_RUNNING') = 0 then
    atom := GlobalAddAtom('PROGRAM_RUNNING')
  else
  begin
    {程序運行則顯示信息然後退出}  // 彆最唗眒堍俴寀珆尨陓洘綴豖堤
    //MessageDlg('程序已經在運行!',mtWarning,[mbOK],0);  // 最唗眒冪婓堍俴

    if MessageDlg('The program is already running!,Whether Quit ?' +chr(13)+ 'If you click No, you will open a program again !',mtWarning,[mbOK,mbNo],0)=mrok then
    Halt
    else
    GlobalDeleteAtom(GlobalFindAtom('PROGRAM_RUNNING'));
  end;
  //ShowMessage(IntToStr(GlobalFindAtom('PROGRAM_RUNNING')));


  //與鎖屏建立通信
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin 
   {程序退出時，從原子表中移走信息}//最唗豖堤奀ㄛ植埻赽桶笢痄軗陓洘
   GlobalDeleteAtom(atom);
   {刪除托盤中圖標}// 刉壺迖攫笢腔芞梓
   Shell_NotifyIcon(NIM_DELETE,@Tray);
end; 

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin 
  {如果倒計時開始，禁止關閉程序}  //彆眒冪羲宎給暮奀ㄛ輦砦壽敕最唗敦諳
  if timer2.Enabled =true then
  begin
   canclose:=false;
   MessageBox(Handle ,'Shutdown countdown has started '+chr(13)+' the program is not allowed to shut down '+chr(13)+' you can click cancel the shutdown button !',PChar(Application.Title ),MB_OK);
  end;
end;
procedure TForm1.FormResize(Sender: TObject);  //這個達不到想要的效果，下面的倒是可以
begin
  if ((not btn_abort.Enabled) or(Edit2.text<>'')) then
  begin
    ShowWindow(Application.Handle,sw_minimize);
    ShowWindow(Application.Handle,sw_hide);
    ShowInTray;
  end  ;
 { case WindowState of
    wsMinimized:
   // if  then self.Visible:=false;//隱藏
  end; }
end;

procedure TForm1.ApplicationEvents1Minimize(Sender: TObject);
var meee:Boolean;
begin
  meee:=False ;
  if btn_abort.Enabled then
  begin
    ////Self.WindowState:= wsMaximized;
    //Self .Top :=(Screen.Height-Self.Height )  div 2 ;
    //Self .Left :=(Screen.Width -Self.Width )  div 2 ;
    Self.Position := poScreenCenter ;
    meee :=True ;
   //// Abort ;
  end;
  if (NOT btn_abort.Enabled) and  IsValidTime(Edit2.text) and(enterbool) and (not meee) and (  (Edit2.text<>time_enter)) then
  begin
    //Edit2.text:=time_enter;
    Label3 .Caption := 'The computer will turn off automatically at '+Edit2.text+' !';
    ShowWindow(Application.Handle,sw_minimize);
    ShowWindow(Application.Handle,sw_hide);
    ShowInTray;
    clickInTray:=False ;
  end ;
  if (not btn_abort.Enabled) and (IsValidTime(Edit2.text)) and(not enterbool)   then
  begin
    ShowWindow(Application.Handle,sw_minimize);
    ShowWindow(Application.Handle,sw_hide);
    ShowInTray;
    clickInTray:=False ;
  end ;

  if (NOT btn_abort.Enabled) and (NOT IsValidTime(Edit2.text)) and(enterbool) and (not meee) then
  begin
    {if IsValidTime(Edit2.text)  then
    begin
      ShowWindow(Application.Handle,sw_minimize);
      ShowWindow(Application.Handle,sw_hide);
      ShowInTray;
    end
    else }
    begin
      //enterbool :=false;
      Edit2.text:=time_enter;
      Label3 .Caption := 'The computer will turn off automatically at '+time_enter+' !';
      ShowWindow(Application.Handle,sw_minimize);
      ShowWindow(Application.Handle,sw_hide);
      ShowInTray;
    end;
    clickInTray:=False ;
  end ;

  {else
  begin
    Application.Restore;
    showmessage('Used only for current day,Please set the shutdown time greater than the current time !');
  end;}
end;

procedure TForm1.Timer3Timer(Sender: TObject);
begin
  inc(Autostartshotdown);
  if Autostartshotdown>60 then
  begin
    Btn_OK.Click ;
    Timer3.Enabled :=False;
  end;
end;

procedure TForm1.FormShow(Sender: TObject);
var sYear,sMonth,sDay,sWeek,sTime: string;
begin
  sYear := FormatDateTime('yyyy',Now);  //Year
  sMonth := FormatDateTime('mm',Now);//Month月    // FormatDateTime('mmm',Now)
  sDay := FormatDateTime('dd',Now);//Day日
  sWeek := FormatDateTime('ddd',Now);//周
  sTime := FormatDateTime(' hh:mm:ss',Now);//時間
  Autostartshotdown:=0;
  Label1 .Caption :=sMonth+'/'+sDay+'/'+sYear;
  Label2 .Caption :=sWeek ;
  if DayOfTheWeek(Now) in[2,4,5] then
  begin
    Edit2.Text := '20:55' ;
  end
  else if DayOfTheWeek(Now) in[1,3] then
  begin
    Edit2.Text := '20:45' ;
  end
  else
    Edit2.Text := '12:15' ;
  Timer5.Enabled :=True ;
  Self.Left :=(Screen.WorkAreaWidth -self.Width )div 2 ;
  Self.Top :=(Screen.WorkAreaHeight -self.Height )div 2 ;
end;

procedure TForm1.RefreshTrayIcon;
var 
hwndTrayToolBar : HWND;
rTrayToolBar : tRect;
x , y : Word; 
begin
  hwndTrayToolBar := GetSysTrayWnd;
  Windows.GetClientRect(hwndTrayToolBar, rTrayToolBar);
  for x:=1 to rTrayToolBar.right-1 do
  begin
    for y:=1 to rTrayToolBar.bottom-1 do
    begin
      SendMessage(hwndTrayToolBar , WM_MOUSEMOVE, 0, MAKELPARAM(x,y));
    end;
  end;
end;

function TForm1.GetOS: TOSVersion;
var 
 OS: TOSVersionInfo;
begin 
  ZeroMemory(@OS,SizeOf(OS));
  OS.dwOSVersionInfoSize := SizeOf(OS);
  GetVersionEx(OS);
  Result := osUnknown;
  if OS.dwPlatformId = VER_PLATFORM_WIN32_NT then
  begin
    case OS.dwMajorVersion of
      3: Result := osNT3;
      4: Result := osNT4;
      5:
      begin
        case OS.dwMinorVersion of
          0: Result:= os2K;
          1: Result:= osXP;
          2: Result:= os2K3;
        end;
      end;
    end;
  end 
  else
  if (OS.dwMajorVersion = 4) and (OS.dwMinorVersion = 0) then
    Result := os95
  else
  if (OS.dwMajorVersion = 4) and (OS.dwMinorVersion = 10) then
    Result := os98
  else
  if (OS.dwMajorVersion = 4) and (OS.dwMinorVersion = 90) then
    Result := osME
end;

function TForm1.GetSysTrayWnd: HWND;
var OS: TOSVersion; 
begin 
  OS := GetOS;
  Result := FindWindow('Shell_TrayWnd', nil);
  Result := FindWindowEx(Result, 0, 'TrayNotifyWnd', nil);
  if(OS in [osXP, os2K3])then
    Result := FindWindowEx(Result, 0, 'SysPager', nil);
  if(OS in [os2K, osXP, os2K3])then
    Result := FindWindowEx(Result, 0, 'ToolbarWindow32', nil);
end;

procedure TForm1.MYWndProc(var Msg: Tmessage);
begin
  case Msg.Msg of
    WM_MYUSER:
       begin
        // Edit1.text:=IntToStr(Msg.LParam);
        // myhandle:=Msg.WParam ;
       end;
    1010:Application .Terminate ;
  end;
end;

procedure TForm1.Edit2Enter(Sender: TObject);
begin
  if ( IsValidTime(Edit2.text)) and (not enterbool )then
  begin
    time_enter:=Edit2.Text ;
    enterbool:=True;
  end;
end;

procedure TForm1.Timer4Timer(Sender: TObject);
begin
  {GetCursorPos(closemenu1)  ;
  if (PopupMenu1.PopupPoint.x>0) and (PopupMenu1.PopupPoint.x<>closemenu1.x)  then
  begin
    //PopupMenu1.Items.Click ;
    //PopupMenu1 .Popup(0,0);
    //PopupMenu1.Items [2].Click ;
  end;

  }

  //檢測鎖屏程式是否在運行，如果鎖屏程式是不正常關閉，則啟動自動關機；
  //
end;

procedure TForm1.Timer5Timer(Sender: TObject);
var
  inifile:TInifile;
  iniFileName,sAppPath:string;
begin
  if wMessageShow=nil then
  try
    sAppPath:=ExtractFilePath(Application.ExeName);
    iniFileName:=sAppPath+'testset.ini';
    inifile:=TInifile.Create(iniFileName);
    if FileExists(pChar(iniFileName)) then
    begin
      //inifile.DeleteKey
      //inifile.EraseSection(TrimLeft(TrimRight(Edit1.Text)));
      //Memo2.Lines.Add (  inifile.ReadString(UpperCase(Edit1.Text),'SQL'+stri,'')) ;//   IniConnect.ReadString(Connection,'Server','');
      //Memo2.Lines.Add (  inifile.ReadString(UpperCase(Edit1.Text),'','')) ;
      //Memo2.Lines.Add (  inifile.ReadString(UpperCase(Edit1.Text),'',''))  ;
      if  inifile.ReadString('Message_HJP','Message_Time','')<>'' then
      begin
        if  (Now >StrToFloat(inifile.ReadString('Message_HJP','Message_Time','10'))) and (inifile.ReadInteger('Message_HJP','Message_Int',0)>0) then
        begin
          inifile.writeinteger('Message_HJP' ,'Message_Int',inifile.ReadInteger('Message_HJP','Message_Int',1)-1);
          Application.Restore;
          SetWindowPos(Handle,HWND_TOPMOST,Left,Top,Width,Height,
               SWP_NOACTIVATE);
          wMessageShow:=TwMessageShow.Create(self);
          wMessageShow.Label2.Caption :='Display times is '+IntToStr(inifile.ReadInteger('Message_HJP','Message_Int',0)) ;
          wMessageShow.Label1.Caption :=DateTimeToStr(StrToFloat(inifile.ReadString('Message_HJP','Message_Time','10'))) ;
          wMessageShow.Left :=Self.Left ;
          wMessageShow.Top:=Self.Top ;
          wMessageShow.Memo1.Lines.Text :=inifile.ReadString('Message_HJP','Message_Text','沒有消息！') ;
          wMessageShow.ShowModal ;
          FreeAndNil(wMessageShow);
        end;

      end;
    end
  finally
    FreeAndNil(inifile);
  end;
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if btn_abort.Enabled then
    action:=caNone
  else
  begin
    action:=caNone;
    clickInTray:=False ;
    FormResize(Sender);
  end;

end;

procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  OldX:=x;
  OldY:=y;
end;

procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
  if ssleft in shift then //按下鼠標左鍵
  begin
    Form1.Left:=Form1.Left+x-Oldx;
    Form1.Top:=Form1.Top+y-Oldy;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  FWinfo: TFlashWInfo;
begin
  FWinfo.cbSize := 20;
  FWinfo.hwnd := Application.Handle;
  FWinfo.dwflags := FLASHW_ALL;
  FWinfo.ucount := 200;
  FWinfo.dwtimeout := 0;
  FlashWindowEx(FWinfo);
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  FWinfo: TFlashWInfo;
begin
  FWinfo.cbSize := 20;
  FWinfo.hwnd := Application.Handle;
  FWinfo.dwflags := FLASHW_STOP;
  FWinfo.ucount := 0;
  FWinfo.dwtimeout := 0;
  FlashWindowEx(FWinfo);
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
  if  wMessageHint=nil then
  begin
    wMessageHint:=TwMessageHint.Create(Self);
    wMessageHint.Left :=Self.Left ;
    wMessageHint.Top:=Self.Top ;
    wMessageHint.ShowModal ;
    FreeAndNil(wMessageHint);
  end;

end;

procedure TForm1.Button4Click(Sender: TObject);
var
  myreg:TRegistry;
  mystr2:TStringList ;
  q:Integer;
begin
ShowMessage('1');
  myreg:=TRegistry.Create;
  mystr2:=TStringList.Create;
  myreg.RootKey:=HKEY_LOCAL_MACHINE;
   // Reg.OpenKey('SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run',true)
 // else
   // Reg.OpenKey('SOFTWARE\Microsoft\windows\CurrentVersion\Run',true);
  if myreg.OpenKey('\SOFTWARE\Microsoft\windows\CurrentVersion\Run',false) then
   begin
      ShowMessage('2');
      if myreg.HasSubKeys then     //是否有子键
      begin
      ShowMessage('3');
        myreg.GetKeyNames(mystr2);    //取子键名列表
        myreg.CloseKey;
        Memo2.Clear;
        for q:=0 to mystr2.Count-1 do
        begin
          Memo2.Lines.Add(mystr2[q]);
        end;

      {if mystr1.IndexOf(mystr2[q])=-1 then
      for q:=0 to mystr2.Count-1 do
      begin
          begin
            showmessage(mystr2[q]);
          end;
      end; }
      end;
  end;
  myreg.Free;
  mystr2.Free;
end;

procedure TForm1.Button5Click(Sender: TObject);
var
  inifile:TInifile;
  iniFileName,sAppPath:string;
begin
  if wMessageShow=nil then
  try
    sAppPath:=ExtractFilePath(Application.ExeName);
    iniFileName:=sAppPath+'testset.ini';
    inifile:=TInifile.Create(iniFileName);
    if FileExists(pChar(iniFileName)) then
    begin
      //inifile.DeleteKey
      //inifile.EraseSection(TrimLeft(TrimRight(Edit1.Text)));
      //Memo2.Lines.Add (  inifile.ReadString(UpperCase(Edit1.Text),'SQL'+stri,'')) ;//   IniConnect.ReadString(Connection,'Server','');
      //Memo2.Lines.Add (  inifile.ReadString(UpperCase(Edit1.Text),'','')) ;
      //Memo2.Lines.Add (  inifile.ReadString(UpperCase(Edit1.Text),'',''))  ;
      if  inifile.ReadString('Message_HJP','Message_Time','')<>'' then
      begin
        //if  (Now >StrToFloat(inifile.ReadString('Message_HJP','Message_Time','10'))) and (inifile.ReadInteger('Message_HJP','Message_Int',0)>0) then
        begin
          //inifile.writeinteger('Message_HJP' ,'Message_Int',inifile.ReadInteger('Message_HJP','Message_Int',1)-1);
          Application.Restore;
          SetWindowPos(Handle,HWND_TOPMOST,Left,Top,Width,Height,
               SWP_NOACTIVATE);
          wMessageShow:=TwMessageShow.Create(self);
          wMessageShow.Label2.Caption :='Display times is '+IntToStr(inifile.ReadInteger('Message_HJP','Message_Int',0)) ;
          wMessageShow.Label1.Caption :=DateTimeToStr(StrToFloat(inifile.ReadString('Message_HJP','Message_Time','10'))) ;
          wMessageShow.Left :=Self.Left ;
          wMessageShow.Top:=Self.Top ;
          wMessageShow.Memo1.Lines.Text :=inifile.ReadString('Message_HJP','Message_Text','沒有消息！') ;
          wMessageShow.ShowModal ;
          FreeAndNil(wMessageShow);
        end;

      end;
    end
  finally
    FreeAndNil(inifile);
  end;
end;

end.




1﹜羲宎粕等雄砐
2﹜蛁聊桶雄砐
3﹜督昢最唗赻雄雄
4﹜數赫昢赻雄雄ㄗ潔諉籵徹督昢最唗ㄘ
5﹜雄源宒赻雄樓婥


